const Base = require('./base.js');
const BigNumber = require('bignumber.js');
const { think } = require('thinkjs');
const cid = require('@4a/cid');
const moment = require('moment');

module.exports = class extends Base {
  async getPayAction() {
    const orders = await this.model('order_list').where({order_no: this.get('no'), user_id: this.getLoginUserId()}).select();

    // const order = await this.model('order_list').where({id: id}).find();
    if (think.isEmpty(orders)) {
      return this.fail('找不到订单信息');
    }

    const orderSn = cid(8, { prefix: 'ZSZF' });
    let total = BigNumber(0);

    for (const item of orders) {
      total = total.plus(BigNumber(item.price));
    }

    const orderInfo = {
      order_sn: orderSn,
      order_no: this.get('no'),
      user_id: this.getLoginUserId(),
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      total_price: total.toNumber(),
      month: moment().format('YYYY-MM'),
      method: '小程序',
      remark: '首付'
    };

    if (this.getLoginUserId() == '9172') {
      orderInfo.status = 1;
      orderInfo.method_txt = 'wx小程序内部';
      await this.model('order_list').where({
        order_no: this.get('no'),
        user_id: this.getLoginUserId()
      }).update({
        status: 10,
        pay_method: 'wx小程序内部',
        pay_time: ['exp', 'CURRENT_TIMESTAMP()']
      });
      await this.model('order_pay').add(orderInfo);
      return this.fail(200, '下单成功');
    }

    await this.model('order_pay').add(orderInfo);

    const rPrice = new BigNumber(total).multipliedBy(new BigNumber(100)).toNumber();
    const user = await this.model('user_list').where({id: this.getLoginUserId()}).find();

    const WeixinSerivce = this.service('pay', 'min');
    try {
      const returnParams = await WeixinSerivce.wxappletPay({
        body: '订单编号：' + orderSn,
        out_trade_no: orderSn,
        total_fee: '' + rPrice,
        // total_fee: '1',
        spbill_create_ip: this.ctx.ip,
        openid: user.weixin_openid
      });

      return this.success(returnParams);
    } catch (err) {
      console.log(err, '微信支付失败');
      return this.fail('微信支付失败');
    }
  }

  async getPaySingleAction() {
    const id = this.get('id');

    const order = await this.model('order_list').where({id: id}).find();
    if (think.isEmpty(order)) {
      return this.fail('找不到订单信息');
    }

    const orderSn = cid(8, { prefix: 'ZSZF' });

    let orderPrice = 0;

    if (order.status === 0) {
      orderPrice = order.price;
    }
    if (order.status === 10 && order.price_back) {
      orderPrice = order.price_back;
    }

    if (order.status === 10 && !order.price_back) {
      return this.fail('等待管理员处理尾款');
    }

    const orderInfo = {
      order_sn: orderSn,
      order_id: order.id,
      user_id: this.getLoginUserId(),
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      total_price: orderPrice,
      month: moment().format('YYYY-MM'),
      method: '小程序',
      remark: order.status === 0 ? '首付' : '尾款'
    };

    if (this.getLoginUserId() == '9172') {
      orderInfo.status = 1;
      orderInfo.method_txt = 'wx小程序内部';

      if (order.status === 0) {
        await this.model('order_list').where({
          id: id
        }).update({
          status: 10,
          pay_method: 'wx小程序内部',
          pay_time: ['exp', 'CURRENT_TIMESTAMP()']
        });
      }
      if (order.status === 10 && order.price_back) {
        await this.model('order_list').where({
          id: id
        }).update({
          status: 20,
          pay_method: 'wx小程序内部',
          pay_time: ['exp', 'CURRENT_TIMESTAMP()']
        });
      }
      await this.model('order_pay').add(orderInfo);
      return this.fail(200, '下单成功');
    }

    await this.model('order_pay').add(orderInfo);

    const rPrice = new BigNumber(orderPrice).multipliedBy(new BigNumber(100)).toNumber();
    const user = await this.model('user_list').where({id: this.getLoginUserId()}).find();

    const WeixinSerivce = this.service('pay', 'min');
    try {
      const returnParams = await WeixinSerivce.wxappletPay({
        body: '订单编号：' + orderSn,
        out_trade_no: orderSn,
        total_fee: '' + rPrice,
        // total_fee: '1',
        spbill_create_ip: this.ctx.ip,
        openid: user.weixin_openid
      });

      return this.success(returnParams);
    } catch (err) {
      console.log(err, '微信支付失败');
      return this.fail('微信支付失败');
    }
  }
};
